from typing import List


class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if len(intervals) < 2:
            return intervals
        intervals.sort(key=lambda x: x[0])
        result = []
        for i in range(len(intervals)-1):
            if intervals[i][1] >= intervals[i+1][0]:
                if intervals[i][1] >= intervals[i+1][1]:
                    intervals[i+1] = intervals[i]
                else:
                    intervals[i+1] = [intervals[i][0], intervals[i+1][1]]
            else:
                result.append(intervals[i])
        result.append(intervals[-1])
        return result


if __name__ == '__main__':
    intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
    x = Solution()
    print(x.merge(intervals))
